﻿
using MathWorks.MATLAB.NET.Arrays;
using net.hipigo;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace AgilentDemo
{
    public partial class SinForm : Form
    {

        /// <summary>
        /// 连接信号源
        /// </summary>
        private Socket _newclient;
        /// <summary>
        /// 信号源控制类
        /// </summary>
        private AglientSignalSourceCtrol _aglientCtrol;

        private string arbFilePath = "";

        private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock);

        public SinForm()
        {
            InitializeComponent();

            //using (var algo = new Class1())
            //{
            //    MWArray A1 = (MWNumericArray)new int[] { 1 };
            //    MWArray A2 = (MWNumericArray)new int[] { 2 };
            //    MWArray f1 = (MWNumericArray)new int[] { 1000 };
            //    MWArray f2 = (MWNumericArray)new int[] { 2000 };
            //    MWArray fs = (MWNumericArray)new int[] { 48000 };

            //    MWArray result = algo.sinFun(A1, A2, f1, f2, fs);
            //    var a = result.ToArray();
            //    Console.WriteLine($"总和={a.GetValue(0, 0)}");

            //}

            using (var algo = new Class1())
            {
                MWArray A1 = (MWNumericArray)new int[] { 1 };
                MWArray A2 = (MWNumericArray)new int[] { 2 };
                MWArray A3 = (MWNumericArray)new int[] { 3 };
                MWArray A4 = (MWNumericArray)new int[] { 4 };
                MWArray A5 = (MWNumericArray)new int[] { 5 };

                MWArray f1 = (MWNumericArray)new int[] { 1000 };
                MWArray f2 = (MWNumericArray)new int[] { 2000 };
                MWArray f3 = (MWNumericArray)new int[] { 3000 };
                MWArray f4 = (MWNumericArray)new int[] { 4000 };
                MWArray f5 = (MWNumericArray)new int[] { 5000 };

                MWArray fs = (MWNumericArray)new int[] { 48000 };
                MWArray time = (MWNumericArray)new float[] { 0.1f };

                MWArray result = algo.sinFun(A1, A2, A3, A4, A5, f1, f2,f3, f4,f5, fs, time);
                var a = result.ToArray();
                int indexLength = a.GetLength(0);
                int rowLength = a.GetLength(1);
                for (int i = 0; i < indexLength; i++) 
                {
                    for (int j = 0; j < rowLength; j++)
                    {
                        var tmp = a.GetValue(i, j);
                        Console.WriteLine($"data={a.GetValue(i, j)}");
                    }
                }
                

            }
        }


        private string ConnectSocket(IPEndPoint ipep, Socket sock)
        {
            string exmessage = "";
            try
            {
                sock.Connect(ipep);
            }
            catch (System.Exception ex)
            {
                exmessage = ex.Message;
            }
            finally
            {
            }
            return exmessage;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string ipStr = ipEt.Text;

            if (ipStr == null || !Regex.IsMatch(ipStr, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase))
            {
                MessageBox.Show("请输入正确的ip！");
                return;
            }
            _newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipStr), 5025);
            if (btnConnect.Text.Equals("连接"))
            {
                try
                {
                    //_newclient.Connect(ie);
                    ConnectSocketDelegate connect = ConnectSocket;
                    IAsyncResult asyncResult = connect.BeginInvoke(ie, _newclient, null, null);

                    bool connectSuccess = asyncResult.AsyncWaitHandle.WaitOne(2000, false); //2秒后结束
                    if (!connectSuccess)
                    {
                        MessageBox.Show(string.Format("连接失败！错误信息：{0}", "连接超时"));//2秒后弹出
                        return;
                    }
                    comboBox2.SelectedIndex = 0;
                    //MessageBox.Show("连接信号源成功！");
                    btnConnect.Text = "断开";
                }
                catch (SocketException)
                {
                    MessageBox.Show("连接信号源失败！");
                    btnConnect.Text = "连接";
                }
            }
            else 
            {
                try
                {
                    _newclient.Close();
                }
                catch (SocketException ex)
                {
                    MessageBox.Show("断开失败！");
                }
                btnConnect.Text = "连接";
            }
            
        }

        private void button14_Click(object sender, EventArgs e)
        {
            if (_newclient == null)
                return;

            float volt = Convert.ToSingle(1.0f);
            string str = string.Format("VOLT +{0}\r\n", volt);
            str += "OUTP 1\r\n";
            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button15_Click(object sender, EventArgs e)
        {
            if (_newclient == null || !_newclient.Connected)
            {
                MessageBox.Show("请连接信号源");
                return;
            }

            if (arbFilePath == null || arbFilePath.Equals("")) 
            {
                MessageBox.Show("请选上传的arb文件");
                return;
            }
            string str = "DATA:VOL:CLEAR\r\n";  // 清空内存中所有任意波形（默认保留EXP_RISE.arb）

            //string temp = @"USB:\0002.arb";
            string wave = @"INT:\TEMPARB.arb";
            str += string.Format("MMEM:DOWN:FNAM \"{0}\"\r\n", wave);

            StreamReader sr = new StreamReader(arbFilePath);
            string mydata = sr.ReadToEnd();
            int length = mydata.Length;
            sr.Close();
            str += string.Format("MMEM:DOWN:DATA #{0}{1}{2}\r\n", length.ToString().Length, length, mydata);
            str += string.Format("MMEM:LOAD:DATA \"{0}\"\r\n", wave);   // 加载任意波形到内存
            str += string.Format("FUNCtion:ARBitrary \"{0}\"\r\n", wave);

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);

            int ret = _newclient.Send(data);
            if (ret != 0)
            {
                MessageBox.Show("上传成功");
                return;
            }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex == 0)
            {
                comboBox1.Items.Clear();
                comboBox1.Items.Add("CARDIAC.arb");
                comboBox1.Items.Add("D_LORENTZ.arb");
                comboBox1.Items.Add("EXP_FALL.arb");
                comboBox1.Items.Add("EXP_RISE.arb");
                comboBox1.Items.Add("GAUSSIAN.arb");
                comboBox1.Items.Add("HAVERSINE.arb");
                comboBox1.Items.Add("LORENTZ.arb");
                comboBox1.Items.Add("NEG_RAMP.arb");
                comboBox1.Items.Add("SINC.arb");
                comboBox1.Items.Add("ARB_hht1.arb");
            }
            else
            {
                comboBox1.Items.Clear();
                comboBox1.Items.Add("0001.arb");
                comboBox1.Items.Add("0002.arb");
                comboBox1.Items.Add("0003.arb");
                comboBox1.Items.Add("0004.arb");
                comboBox1.Items.Add("0005.arb");
                comboBox1.Items.Add("0006.arb");
            }
            comboBox1.SelectedIndex = 0;
        }

        private void fileSelectBtn_Click(object sender, EventArgs e)
        {
            // 1. 打开文件管理器选择文件
            OpenFileDialog openFileDialog1 = new OpenFileDialog();  //显示选择文件对话框
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "arb files (*.arb)|*.arb|All files (*.*)|*.*"; //所有的文件格式
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = false;

            // 2. 查看可执行文件路径
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //updateTextBoxContent(openFileDialog1.FileName);// 这一步, 我是查看文件路径, 就是输出路径
                try
                {
                    // 3. 根据可执行文件的路径, 调用该可执行文件
                    string path = openFileDialog1.FileName;
                    FileInfo file = new FileInfo(path);
                    arbFilePath = path;
                    fileTv.Text = "文件地址：" + path;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("执行失败 错误原因:" + ex.Message);
                }
            }

        }
    }
}
